package org.harsh.transmission.common;

import io.netty.handler.traffic.GlobalTrafficShapingHandler;
import io.netty.handler.traffic.TrafficCounter;
import io.netty.util.concurrent.DefaultEventExecutorGroup;
import io.netty.util.concurrent.EventExecutorGroup;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.TimeUnit;

/**
 * 全局流量控制
 */
@Slf4j
public class GlobalTraffic {
    private static long totalWriteLimit;
    private static long totalReadLimit;

    private static final EventExecutorGroup EXECUTOR_GROUOP = new DefaultEventExecutorGroup(Runtime.getRuntime().availableProcessors() * 2);
    private static GlobalTrafficShapingHandler globalTrafficHandler;

    public static synchronized GlobalTrafficShapingHandler getInstance() {
        if(globalTrafficHandler == null) {
            globalTrafficHandler = new GlobalTrafficShapingHandler(EXECUTOR_GROUOP,  totalWriteLimit,  totalReadLimit);
        }
        return globalTrafficHandler;
    }

    static  {
        totalWriteLimit = 10 * 1024 * 1024;
        totalReadLimit = 10 * 1024 * 1024;
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    TrafficCounter trafficCounter = GlobalTraffic.getInstance().trafficCounter();
                    try {
                        TimeUnit.SECONDS.sleep(10);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    final long totalRead = trafficCounter.cumulativeReadBytes();
                    final long totalWrite = trafficCounter.cumulativeWrittenBytes();
//                    log.info("【流量监控】total read: {} KB, total write: {} KB ,channel read: {} KB ,channel write :{} KB",
//                            (totalRead >> 10) ,
//                            (totalWrite >> 10),
//                            (trafficCounter.currentReadBytes() >> 10),
//                            (trafficCounter.currentWrittenBytes() >> 10));
                }
            }
        }).start();
    }


}
